package com.example.societiesSystem.service.impl;

import com.example.societiesSystem.service.EmailService;
import com.example.societiesSystem.utils.EncryptUtils;
import com.example.societiesSystem.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

/**
 * @Author：G-L
 * @Version：1.0
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendEmail;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void putEmail(String email)  {
        //生成6未随机验证码使用随机数实现
        String numbers = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(numbers.length());
            sb.append(numbers.charAt(index));
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendEmail);
        message.setTo(email);
        message.setSubject("登录验证码");
        message.setText("您的验证码为：" + sb);
        javaMailSender.send(message);

        redisUtil.set(email, sb.toString(), 60 * 5);



//        Properties props = new Properties();
//        props.put("mail.smtp.host", "smtp.qq.com"); // QQ邮箱的SMTP服务器地址
//        props.put("mail.smtp.auth", "true"); // 启用SMTP认证
//        props.put("mail.smtp.port", "587"); // QQ邮箱的SMTP端口
//        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS
//
//        // 创建邮件会话
//        Session session = Session.getInstance(props, null);
//
//        // 创建邮件
//        Message message = new MimeMessage(session);
//        message.setFrom(new InternetAddress(sendEmail)); // 设置发件人
//        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); // 设置收件人
//        message.setSubject("登录验证码"); // 设置邮件主题
//        message.setText("您的验证码为：" + sb); // 设置邮件内容
//
//        // 发送邮件
//        Transport transport = session.getTransport("smtp");
//        transport.connect(username, password);
//        transport.sendMessage(message, message.getAllRecipients());
//        transport.close();



    }
}
